// 加载媒体文件
async function loadMediaFiles() {
    try {
        const response = await fetch('/api/gallery/files');
        const files = await response.json();
        renderMediaFiles(files);
    } catch (error) {
        console.error('加载文件失败:', error);
    }
}

// 渲染媒体文件
function renderMediaFiles(files) {
    const galleryContainer = document.getElementById('galleryContainer');
    galleryContainer.innerHTML = '';
    
    files.forEach(file => {
        const mediaItem = document.createElement('div');
        mediaItem.className = 'media-item';
        
        if (file.type === 'video') {
            // 显示视频缩略图和播放按钮
            mediaItem.innerHTML = `
                <div style="width:100%;height:100%;background:#000;display:flex;align-items:center;justify-content:center;position:relative;">
                    <video style="width:100%;height:100%;object-fit:cover;position:absolute;top:0;left:0;" muted preload="metadata"></video>
                    <svg viewBox="0 0 24 24" width="40" height="40" fill="white" style="z-index:1;">
                        <path d="M8 5v14l11-7z"/>
                    </svg>
                    <div style="position:absolute;top:5px;left:5px;background:rgba(0,0,0,0.5);color:white;padding:2px 5px;border-radius:3px;font-size:10px;z-index:1;">视频</div>
                </div>
                <button class="delete-btn" data-filename="${file.name}">×</button>
            `;
            
            // 加载视频缩略图
            const videoElement = mediaItem.querySelector('video');
            videoElement.src = file.path;
            
            // 视频加载元数据后，跳转到第一帧
            videoElement.addEventListener('loadedmetadata', function() {
                this.currentTime = 0.01; // 设置到第一帧
            });
            
            // 视频加载第一帧后，暂停播放
            videoElement.addEventListener('loadeddata', function() {
                this.pause();
            });
            
            // 点击时播放视频
            mediaItem.addEventListener('click', (e) => {
                if (!e.target.classList.contains('delete-btn')) {
                    if (videoElement.paused) {
                        videoElement.controls = true;
                        videoElement.play();
                    } else {
                        videoElement.pause();
                    }
                }
            });
        } else if (file.type === 'image') {
            mediaItem.innerHTML = `
                <img src="${file.path}" alt="${file.name}">
                <button class="delete-btn" data-filename="${file.name}">×</button>
            `;
            // 点击图片时在新窗口打开
            mediaItem.querySelector('img').addEventListener('click', (e) => {
                e.stopPropagation();
                window.open(file.path, '_blank');
            });
        } else {
            // 处理非图片和视频文件
            const fileExtension = file.name.split('.').pop().toUpperCase();
            mediaItem.innerHTML = `
                <div style="width:100%;height:100%;background:#f0f0f0;display:flex;flex-direction:column;align-items:center;justify-content:center;position:relative;">
                    <svg viewBox="0 0 24 24" width="40" height="40" fill="#999" style="margin-bottom:10px;">
                        <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                    </svg>
                    <div style="font-size:12px;color:#666;text-align:center;padding:0 5px;word-break:break-word;">${fileExtension}</div>
                    <div style="position:absolute;top:5px;left:5px;background:rgba(0,0,0,0.5);color:white;padding:2px 5px;border-radius:3px;font-size:10px;z-index:1;">文件</div>
                </div>
                <button class="delete-btn" data-filename="${file.name}">×</button>
            `;
            
            // 点击文件时下载
            mediaItem.addEventListener('click', (e) => {
                if (!e.target.classList.contains('delete-btn')) {
                    window.open(file.path, '_blank');
                }
            });
        }
        
        galleryContainer.appendChild(mediaItem);
    });

    // 添加删除事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            e.stopPropagation();
            const filename = btn.getAttribute('data-filename');
            if (confirm('确定要删除这个文件吗？')) {
                try {
                    const response = await fetch(`/api/gallery/files/${filename}`, {
                        method: 'DELETE'
                    });
                    const result = await response.json();
                    if (result.success) {
                        loadMediaFiles();
                    }
                } catch (error) {
                    console.error('删除文件失败:', error);
                }
            }
        });
    });
}

// 上传功能
document.getElementById('uploadBtn').addEventListener('click', () => {
    document.getElementById('fileInput').click();
});

document.getElementById('fileInput').addEventListener('change', async (e) => {
    const files = e.target.files;
    if (files.length > 0) {
        // 获取上传按钮并更新状态
        const uploadBtn = document.getElementById('uploadBtn');
        const originalBtnText = uploadBtn.textContent;
        uploadBtn.textContent = '上传中...';
        uploadBtn.disabled = true;

        // 显示进度条
        const progressContainer = document.getElementById('uploadProgressContainer');
        const progressBar = document.getElementById('uploadProgressBar');
        const progressText = document.getElementById('uploadProgressText');
        
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        progressText.textContent = '0%';

        try {
            // 逐个上传文件
            for (let i = 0; i < files.length; i++) {
                await uploadFileWithChunks(files[i], (progress) => {
                    // 更新进度条显示
                    const overallProgress = Math.round(((i + progress) / files.length) * 100);
                    progressBar.style.width = overallProgress + '%';
                    progressText.textContent = overallProgress + '%';
                });
            }
            
            // 完成上传
            progressBar.style.width = '100%';
            progressText.textContent = '100%';
            
            // 重新加载文件列表
            loadMediaFiles();
        } catch (error) {
            console.error('上传失败:', error);
        } finally {
            // 恢复上传按钮状态
            uploadBtn.textContent = originalBtnText;
            uploadBtn.disabled = false;
            
            // 隐藏进度条
            setTimeout(() => {
                progressContainer.style.display = 'none';
            }, 500);
            
            // 重置文件输入
            e.target.value = '';
        }
    }
});

/**
 * 使用分片上传单个文件
 * @param {File} file - 要上传的文件
 * @param {Function} onProgress - 进度回调函数
 */
async function uploadFileWithChunks(file, onProgress) {
    const CHUNK_SIZE = 20 * 1024 * 1024; // 20MB 每个分片
    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
    const fileId = Date.now() + '-' + Math.random().toString(36).substr(2, 9);
    
    for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
        const start = chunkIndex * CHUNK_SIZE;
        const end = Math.min(start + CHUNK_SIZE, file.size);
        const chunk = file.slice(start, end);
        
        const formData = new FormData();
        formData.append('chunk', chunk);
        formData.append('fileId', fileId);
        formData.append('fileName', file.name);
        formData.append('chunkIndex', chunkIndex);
        formData.append('totalChunks', totalChunks);
        
        const response = await fetch('/api/gallery/upload-chunk', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (!result.success) {
            throw new Error('上传分片失败: ' + result.error);
        }
        
        // 更新进度
        onProgress((chunkIndex + 1) / totalChunks);
    }
}

// 初始化加载
loadMediaFiles();